package com.zy.demo048084.config;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

// 启动类中配置负载均衡。不适用[@Configuration]
public class OpenFeignConfig {

    @Bean
    public ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment e, LoadBalancerClientFactory factory) {
        // 获取负载均衡服务名称
        String name = e.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        // 从所有服务提供者的列表中随机选择一个实例
        return new RandomLoadBalancer(factory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
    }
}
